/**
 * Created by Bin_Shi on 2016/11/17.
 * websocket相关
 */

function getWebSocket(){
    if(window.WebSocket == undefined) {
        return false;
    }
    var connection = new WebSocket('ws://192.168.1.176:8283');
    //设定WebSocket开启事件
    connection.onopen = function(event){
        console.log('WebSocket连接成功');
        ready = true;
        requestAnimationFrame(animate);
    };

    //设定WebSocket关闭事件
    connection.onclose = function(){

    };

    //接收WebSocket服务器发来的数据
    connection.onmessage = function(event){
        var data = JSON.parse(event.data);
        //console.log(data);
        if(data.type == 'welcome'){
            ID = data.id;
        }
        if(data.type == 'update'){
            if(data.id == ID){
                return false;
            }
            else{
                var other_player = createPlayer(data);
                others[other_player.id] = other_player;
            }
        }
    };

    //处理WebSocket错误
    connection.onerror = function(event){
        console.log(event.data);
    };

    return connection;
}


//向WebSocket服务器发送数据
function wsSend(connection, player){
    var data = {
        type:'update',
        id:player.id,
        x:player.x,
        y:player.y,
        alive:player.alive,
        name:player.name,
        color:player.color,
        t_x:player.t_x,
        t_y:player.t_y,
        v:player.v
    };
    connection.send(JSON.stringify(data));
}
